<?php

use Medoo\Medoo;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('../..') . '/vendor/autoload.php';
$config = include '../database.php';
const BRAND = '宝马';
echo '爬虫开始' . PHP_EOL;

$db = new Medoo($config);
$db->delete('charger', ['brand' => BRAND]);

$client = new GuzzleHttp\Client();

$res = $client->get(
    'https://cn-digital2-app.bmw.com.cn/dlo/init', [
        'headers' => [
            'Referer' => 'https://www.minichina.com.cn/zh_CN/home/dlo.html',
        ]
    ]
);
$html = (string)$res->getBody();
preg_match('/{"provinces":\[(?<provinces>.*?)\],"cities":\[(?<cities>.*?)\]/', $html, $m);

$provinces = json_decode('[' . $m['provinces'] . ']', true);


$cities = json_decode('[' . $m['cities'] . ']', true);

$dict = [];
array_map(static function ($item) use (&$dict) {
    $dict[$item['id']] = $item['nz'];
}, array_merge($provinces, $cities));


$res = $client->get('https://www.bmw.com.cn/zh/fastlane/dealer-locator.html');
$html = (string)$res->getBody();
$ok = preg_match('/id="headerKey" value="(.*)"/', $html, $m);
if ($ok) {
    $key = $m[1];
} else {
    $key = '';
    echo 'error';
}


foreach ($provinces as $p) {
    $res = $client->get('https://cn-digital2-app.bmw.com.cn/dlo/v1/outlets?brand_id=1&province_id=' . $p['id'],
        [
            'headers' => [
                'ServiceKey' => $key,
            ]
        ]);
    $html = (string)$res->getBody();

    $tmp = json_decode($html, true);
    $dealers = $tmp['data'];


    foreach ($dealers as $item) {

        $service_types = $item['service_types'];

        $result = array_filter($service_types, static function ($s) {
            return $s['code'] === '30';
        });


        if (empty($result)) {
            continue;
        }

        $note = array_pop($result)['name_cn'];

        $db->insert('charger', [
            'brand' => BRAND,
            'province' => $dict[$item['province_id']],
            'city' => $dict[$item['city_id']],
            'title' => $item['name_cn'],
            'address' => $item['addr_cn'],
            'tel' => $item['tel'],
            'lng' => $item['lng'],
            'lat' => $item['lat'],
            'note' => $note,
        ]);
        echo "{$item['name_cn']}完成" . PHP_EOL;
    }


}


echo '爬虫结束' . PHP_EOL;

